<?php

require ('User.class.php');
require ('Site.class.php');
class UserManager {

    private $connection;
    
    const CHECK_LOGIN = "SELECT * FROM users WHERE username = :username AND password = :password;";
    const GET_PERMISSIONS = "SELECT * FROM users_permissions WHERE user_id = :user_id;";
    
    public function __construct() {
        $this->connection = new PDO(
                        "mysql:host=" . Site::DB_HOST . ";dbname=" . Site::DB_NAME,
                        Site::DB_USERNAME,
                        Site::DB_PASSWORD,
                        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
        );
    }
    
    public function check_login($username, $password) {
        
        $stmt_u = $this->connection->prepare(self::CHECK_LOGIN);
        
        $stmt_u->execute(array(
                        'username' => $username,
                        'password' => $password
                    ));
        $user = null;
        if ($stmt_u->rowCount() > 0) {
            $user = new User();
            $u = $stmt_u->fetch(PDO::FETCH_ASSOC);
            
            foreach ($u as $key => $value) {
                $user->{$key} = $value;
            }
            
            $stmt_p = $this->connection->prepare(self::GET_PERMISSIONS);
            $stmt_p->execute(array('user_id' => $u['id']));
            $p = array();
            while ($p_t = $stmt_p->fetch(PDO::FETCH_ASSOC)) {
                array_push($p, $p_t['permission_id']);
            }
            
            $user->permissions = $p;
        }
        
        return $user;
        
    }

}

?>
